#!/bin/bash

echo "🚀 开始部署PT项目到阿里云服务器..."

# 检查Docker和Docker Compose是否安装
check_docker() {
    if ! command -v docker &> /dev/null; then
        echo "❌ Docker 未安装，正在安装..."
        curl -fsSL https://get.docker.com | bash
        systemctl start docker
        systemctl enable docker
        usermod -aG docker $USER
    else
        echo "✅ Docker 已安装"
    fi
}

check_docker_compose() {
    if ! command -v docker-compose &> /dev/null; then
        echo "❌ Docker Compose 未安装，正在安装..."
        curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
        chmod +x /usr/local/bin/docker-compose
    else
        echo "✅ Docker Compose 已安装"
    fi
}

# 1. 编译项目
echo "📦 编译Spring Boot项目..."
mvn clean package -DskipTests

if [ ! -f "target/my-pt-1.0-SNAPSHOT.jar" ]; then
    echo "❌ 编译失败，请检查Maven配置"
    exit 1
fi

# 2. 检查Docker环境
check_docker
check_docker_compose

# 3. 停止已存在的容器（如果有）
echo "🛑 停止现有容器..."
docker-compose down

# 4. 构建和启动服务
echo "🔧 构建Docker镜像..."
docker-compose build

echo "🚀 启动服务..."
docker-compose up -d

# 5. 检查服务状态
echo "⏳ 等待服务启动..."
sleep 30

echo "📊 检查服务状态..."
docker-compose ps

# 6. 检查应用健康状态
echo "🏥 检查应用健康状态..."
for i in {1..10}; do
    if curl -f http://localhost:8080/actuator/health &> /dev/null; then
        echo "✅ 应用启动成功！"
        break
    else
        echo "⏳ 等待应用启动... ($i/10)"
        sleep 10
    fi
done

echo "🎉 部署完成！"
echo "📄 查看日志: docker-compose logs -f pt-app"
echo "🌐 访问地址: http://服务器IP:8080"
echo "📚 API文档: http://服务器IP:8080/doc.html" 